{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "7bef0e88",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "1、告警内容理解。根据输入的告警信息，结合第三方接口数据，判断当前的异常情况（告警对象、异常模式）；\n",
    "2、分析方法建议。根据当前告警内容，结合应急预案、运维文档和大语言模型自有知识，形成分析方法的建议；\n",
    "3、分析内容自动提取。根据用户输入的分析内容需求，调用多种第三方接口获取分析数据，并进行总结；\n",
    "4、处置方法推荐和执行。根据当前上下文的故障场景理解，结合应急预案和第三方接口，形成推荐处置方案，待用户确认后调用第三方接口进行执行。\n",
    "\"\"\"\n",
    "import json\n",
    "import os\n",
    "import random\n",
    "import dashscope\n",
    "from dashscope.api_entities.dashscope_response import Role\n",
    "dashscope.api_key = \"sk-你的KEY\"\n",
    "from openai import OpenAI\n",
    "\n",
    "# 通过第三方接口获取数据库服务器状态\n",
    "def get_current_status():\n",
    "    # 生成连接数数据\n",
    "    connections = random.randint(10, 100)\n",
    "    # 生成CPU使用率数据\n",
    "    cpu_usage = round(random.uniform(1, 100), 1)\n",
    "    # 生成内存使用率数据\n",
    "    memory_usage = round(random.uniform(10, 100), 1)\n",
    "    status_info = {\n",
    "        \"连接数\": connections,\n",
    "        \"CPU使用率\": f\"{cpu_usage}%\",\n",
    "        \"内存使用率\": f\"{memory_usage}%\"\n",
    "    }\n",
    "    return json.dumps(status_info, ensure_ascii=False)\n",
    "\n",
    "# 封装模型响应函数\n",
    "def get_response(messages):\n",
    "    response = dashscope.Generation.call(\n",
    "        model='qwen-turbo',\n",
    "        messages=messages,\n",
    "        tools=tools,\n",
    "        result_format='message'  # 将输出设置为message形式\n",
    "    )\n",
    "    return response\n",
    "    \n",
    "current_locals = locals()\n",
    "current_locals\n",
    "\n",
    "tools = [\n",
    "        {\n",
    "            \"type\": \"function\",\n",
    "            \"function\": {\n",
    "                \"name\": \"get_current_status\",\n",
    "                \"description\": \"调用监控系统接口，获取当前数据库服务器性能指标，包括：连接数、CPU使用率、内存使用率\",\n",
    "                \"parameters\": {\n",
    "                },\n",
    "                \"required\": []\n",
    "            }                \n",
    "        }\n",
    "    ]\n",
    "\n",
    "query = \"\"\"告警：数据库连接数超过设定阈值\n",
    "时间：2024-08-03 15:30:00\n",
    "\"\"\"\n",
    "messages=[\n",
    "    {\"role\": \"system\", \"content\": \"我是运维分析师，用户会告诉我们告警内容。我会基于告警内容，判断当前的异常情况（告警对象、异常模式）\"},\n",
    "    {\"role\": \"user\", \"content\": query}]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "cf958f2b-b56c-4c4a-b957-356cbed3dcac",
   "metadata": {},
   "outputs": [],
   "source": [
    "while True:\n",
    "    response = get_response(messages)\n",
    "    message = response.output.choices[0].message\n",
    "    messages.append(message)\n",
    "    #print('response=', response)\n",
    "\n",
    "    if response.output.choices[0].finish_reason == 'stop':\n",
    "        break\n",
    "    \n",
    "    # 判断用户是否要call function\n",
    "    if message.tool_calls:\n",
    "        # 获取fn_name, fn_arguments\n",
    "        fn_name = message.tool_calls[0]['function']['name']\n",
    "        fn_arguments = message.tool_calls[0]['function']['arguments']\n",
    "        arguments_json = json.loads(fn_arguments)\n",
    "        #print(f'fn_name={fn_name} fn_arguments={fn_arguments}')\n",
    "        function = current_locals[fn_name]\n",
    "        tool_response = function(**arguments_json)\n",
    "        tool_info = {\"name\": \"get_current_weather\", \"role\":\"tool\", \"content\": tool_response}\n",
    "        #print('tool_info=', tool_info)\n",
    "        messages.append(tool_info)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "9534f59c-eeb4-4d1b-9943-a08e9d8ca104",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'role': 'system',\n",
       "  'content': '我是运维分析师，用户会告诉我们告警内容。我会基于告警内容，判断当前的异常情况（告警对象、异常模式）'},\n",
       " {'role': 'user', 'content': '告警：数据库连接数超过设定阈值\\n时间：2024-08-03 15:30:00\\n'},\n",
       " Message({'role': 'assistant', 'content': '', 'tool_calls': [{'function': {'name': 'get_current_status', 'arguments': '{}'}, 'index': 0, 'id': 'call_4d62cc2e5fb5474ca248a0', 'type': 'function'}]}),\n",
       " {'name': 'get_current_weather',\n",
       "  'role': 'tool',\n",
       "  'content': '{\"连接数\": 37, \"CPU使用率\": \"58.9%\", \"内存使用率\": \"29.4%\"}'},\n",
       " Message({'role': 'assistant', 'content': '当前数据库连接数为37，已超过通常设定的阈值。目前的CPU使用率为58.9%，内存使用率为29.4%。从当前数据来看，高连接数可能是由于当前时段的业务高峰导致的，建议进一步检查具体是哪些业务在占用连接资源，并考虑优化数据库连接池配置或者对高峰期的连接请求进行限流处理。'})]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "messages"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
